﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Holoville.HOTween;

public partial class MessageScene : Scene
{
	public BattleMessageScrollView battleMessageScrollView;
	public UIGrid battleMessageGrid;
	public GameObject battleMessageCell;
	public ObjectPooler battleMessageObjectPooler;

	int lastOpenedBattleMessageCellIndex = -1;

	Dictionary<int, BattleMessage> battleMessageDictionary = new Dictionary<int, BattleMessage>();
	Dictionary<int, GameObject> battleMessageObjectDictionary = new Dictionary<int, GameObject>();

	public void OnChange_SelectAllBattleMessageCheckBox()
	{
		bool checkValue = false;

		// 한 개라도 체크 되어있지 않으면, 전체선택으로 간주함
		foreach (KeyValuePair<int, GameObject> pair in battleMessageObjectDictionary)
		{
			if (selectAllBattleMessageToggle.value == false)
				break;

			if (pair.Value.GetComponent<BattleMessageCell>().toggle.value == false)
			{
				checkValue = true;
				break;
			}
		}
		
		selectAllBattleMessageToggle.value = checkValue;
		
		List<int> keyList = new List<int>(battleMessageObjectDictionary.Keys);
		
		foreach (KeyValuePair<int, GameObject> pair in battleMessageObjectDictionary)
		{
			pair.Value.GetComponent<BattleMessageCell>().toggle.value = checkValue;
		}
	}

	void ClearBattleMessage()
	{
		lastOpenedBattleMessageCellIndex = -1;
		battleMessageDictionary.Clear();

		foreach (KeyValuePair<int, GameObject> pair in battleMessageObjectDictionary)
		{
			pair.Value.GetComponent<BattleMessageCell>().toggle.value = false;
			NGUITools.SetActive(pair.Value, false);

		}
		battleMessageObjectDictionary.Clear();
	}

	public void LoadBattleMessage()
	{
		ClearBattleMessage();
		lastOpenedBattleMessageCellIndex = -1;

		NetworkManager.Instance.C2S_MSG_LIST<List<BattleMessage>>((int)TAB_TYPE.BATTLE_MESSAGE, (responseData) => {
			GameObject g = null;
			int idx = 0;

			ShowBadge(BadgeType.BattleMessage);

			List<BattleMessage> tempBattleMessageList = new List<BattleMessage>();
			foreach (BattleMessage bm in responseData.data)
			{
				if (bm.msgCategory == (short)MSG_BATTLE_CATEGORY.IV || bm.msgCategory == (short)MSG_BATTLE_CATEGORY.CA)
					tempBattleMessageList.Add(bm);
			}
			responseData.data = tempBattleMessageList;

			if (responseData.data.Count <= 0)
			{
				SetEmptyListView(true);
				return;
			}

			SetEmptyListView(false);
			
			responseData.data = responseData.data.OrderByDescending(battleMessage=>battleMessage.date).ToList();

			string invasionWinTemplate = Localization.Get ("uiMailboxInvasionTitle2"); // [침략] {0} 님의 침략에 성공하였습니다.
			string invasionDefeatTemplate = Localization.Get ("uiMailboxInvasionTitle1"); // [침략] {0} 님의 침략에 패배하였습니다.
			string counterAttackWinTemplate = Localization.Get ("uiMailboxInvasionTitle4"); // [반격] {0} 님의 반격에 성공하였습니다.
			string counterAttackDefeatTemplate = Localization.Get ("uiMailboxInvasionTitle3"); // [반격] {0} 님의 반격에 패배하였습니다.

			foreach (BattleMessage bm in responseData.data)
			{
				g = battleMessageObjectPooler.GetPooledObject();
				g.transform.parent = battleMessageGrid.transform;
				g.transform.localScale = Vector3.one;
				g.transform.localRotation = Quaternion.identity;
				
				BattleMessageCell bmc = g.GetComponent<BattleMessageCell>();
				bmc.indexPath = idx;

				bmc.expLabel.text = string.Format("+{0}", bm.exp.ToString());
				bmc.receiveDateLabel.text =  DatetimeToString(bm.date);
				bmc.remainTimeLabel.text = DatetimeToFomattedString(bm.date);

				switch(bm.msgCategory)
				{
				case (short)MSG_BATTLE_CATEGORY.IV:
					NGUITools.SetActive(bmc.counterAttackButton, true);
					bmc.titleLabel.text = string.Format((bm.isWin ? invasionWinTemplate : invasionDefeatTemplate), bm.ivUserName);
					bmc.subTitleLabel.text = Localization.Get("MailInvasionInvasionResult");
					bmc.battleResutLabel.text = Localization.Get(bm.isWin ? "MailInvasionInvadeWin" : "MailInvasionInvadeLose");
					break;
				case (short)MSG_BATTLE_CATEGORY.CA:
					NGUITools.SetActive(bmc.counterAttackButton, false);
					bmc.titleLabel.text = string.Format((bm.isWin ? counterAttackWinTemplate : counterAttackDefeatTemplate), bm.ivUserName);
					bmc.subTitleLabel.text = Localization.Get("MailInvasionCounterResult");
					bmc.battleResutLabel.text = Localization.Get(bm.isWin ? "MailInvasionInvadeWin" : "MailInvasionInvadeLose");
					break;
				default:
					NGUITools.SetActive(bmc.counterAttackButton, false);
					break;
				}

				for (int i = 0; i < bm.memExp.Count; i++)
				{
					if (bm.memExp[i][0] != 0)
					{
						bmc.memberNameLabelArray[i].text = Localization.Get(string.Format("charName{0}", bm.memExp[i][0].ToString()));
						bmc.memberExpLabelArray[i].text = string.Format("+{0}", bm.memExp[i][1].ToString());
						NGUITools.SetActive(bmc.memberExpIconArray[i], true);
					}
					else
					{
						bmc.memberNameLabelArray[i].text = string.Empty;
						bmc.memberExpLabelArray[i].text = string.Empty;
						NGUITools.SetActive(bmc.memberExpIconArray[i], false);
					}
				}

				battleMessageObjectDictionary.Add (idx, g);
				battleMessageDictionary.Add (idx, bm);
				
				NGUITools.SetActive(g, true);
				
				g.animation["View_message Open"].time = 0.0f;
				g.animation["View_message Open"].enabled = true;
				g.animation.Sample();
				g.animation["View_message Open"].enabled = false;
				
				idx++;
			}
			
			battleMessageGrid.Reposition();
			battleMessageScrollView.ResetPosition();

		});
		
	}

	public void OnClick_RemoveBattleMessage()
	{
		Debug.Log ("OnClick_RemoveBattleMessage");
		foreach (KeyValuePair<int, GameObject> pair in battleMessageObjectDictionary)
		{
			if (pair.Value.GetComponent<BattleMessageCell>().toggle.value == true)
			{
				RemoveBattleMessage(pair.Key, 2);
			}
		}
	}
	
	public void OnClick_RefreshBattleMessage()
	{
		Debug.Log("OnClick_RefreshBattleMessage");
		LoadBattleMessage();
	}

	public void CounterAttackProcess(int selectedIndexPath)
	{
        UserData.Instance.isQuickPVPBattle = true;
		UserData.Instance.counterAttackMsgId = battleMessageDictionary[selectedIndexPath].id;
		SceneController.LoadLevel("Lobby_4vs4");
	}

	void RemoveBattleMessage(int selectedKey, int msgType)
	{
		NetworkManager.Instance.C2S_MSG_REMOVE(battleMessageDictionary[selectedKey].id, msgType, (responseData) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}

			LoadBattleMessage();
		});
	}

	public void FlipOpenBattleMessageCell(int selectedIndexPath)
	{
		int tweenStartIndex = 0;
		int tweenEndIndex = 0;
		float tweenValue = 0.0f;
		
		battleMessageObjectDictionary[selectedIndexPath].GetComponent<BattleMessageCell>().animation.Play("View_message Open");
		
		if (lastOpenedBattleMessageCellIndex >= 0)
		{
			battleMessageObjectDictionary[lastOpenedBattleMessageCellIndex].GetComponent<BattleMessageCell>().animation.Play("View_message Close");
			
			if (selectedIndexPath < lastOpenedBattleMessageCellIndex)
			{
				tweenStartIndex = selectedIndexPath + 1;
				tweenEndIndex = lastOpenedBattleMessageCellIndex;
				tweenValue = -519.0f;
			}
			else
			{
				tweenStartIndex = lastOpenedBattleMessageCellIndex + 1;
				tweenEndIndex = selectedIndexPath;
				tweenValue = 519.0f;
			}
		}
		else
		{
			tweenStartIndex = selectedIndexPath + 1;
			tweenEndIndex = battleMessageObjectDictionary.Count - 1;
			tweenValue = -519.0f;
		}
		
		for (int i = tweenStartIndex; i <= tweenEndIndex; i++)
		{
			HOTween.To(battleMessageObjectDictionary[i].transform, 0.3f, new TweenParms().Prop("localPosition", new Vector3(0.0f, tweenValue, 0.0f), true));
		}
		
		lastOpenedBattleMessageCellIndex = selectedIndexPath;
	}
	
	public void FlipCloseBattleMessageCell(int selectedIndexPath)
	{
		int tweenStartIndex = selectedIndexPath + 1;
		int tweenEndIndex = battleMessageObjectDictionary.Count - 1;
		float tweenValue = 519.0f;
		
		battleMessageObjectDictionary[selectedIndexPath].GetComponent<BattleMessageCell>().animation.Play("View_message Close");
		
		for (int i = tweenStartIndex; i <= tweenEndIndex; i++)
		{
			HOTween.To(battleMessageObjectDictionary[i].transform, 0.3f, new TweenParms().Prop("localPosition", new Vector3(0.0f, tweenValue, 0.0f), true));
		}
		
		lastOpenedBattleMessageCellIndex = -1;
	}
}
